package com.whmskj.xjlhbc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whmskj.xjlhbc.domain.CompletionOfProductionDayBctj14;
import com.whmskj.xjlhbc.dto.DailyProductionQueryDto;
import com.whmskj.xjlhbc.mapper.CompletionOfProductionDayBctj14Mapper;
import com.whmskj.xjlhbc.service.ICompletionOfProductionDayBctj14Service;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * BC-TJ-14产量日完成情况Service实现类
 */
@Service
public class CompletionOfProductionDayBctj14ServiceImpl
        extends ServiceImpl<CompletionOfProductionDayBctj14Mapper, CompletionOfProductionDayBctj14>
        implements ICompletionOfProductionDayBctj14Service {

    @Override
    public List<Map<String, Object>> queryList(DailyProductionQueryDto queryDto) {
        LambdaQueryWrapper<CompletionOfProductionDayBctj14> wrapper = new LambdaQueryWrapper<>();

        // 如果指定了起止日期，按日期范围查询
        if (StringUtils.hasText(queryDto.getStartDate()) && StringUtils.hasText(queryDto.getEndDate())) {
            wrapper.ge(CompletionOfProductionDayBctj14::getStatisticsDate, queryDto.getStartDate());
            wrapper.le(CompletionOfProductionDayBctj14::getStatisticsDate, queryDto.getEndDate());
        } else if (queryDto.getYear() != null && queryDto.getMonth() != null) {
            // 如果指定了年月，按业务月份查询（上月21号到本月20号）
            String startDate = getBusinessMonthStartDate(queryDto.getYear(), queryDto.getMonth());
            String endDate = getBusinessMonthEndDate(queryDto.getYear(), queryDto.getMonth());
            wrapper.ge(CompletionOfProductionDayBctj14::getStatisticsDate, startDate);
            wrapper.le(CompletionOfProductionDayBctj14::getStatisticsDate, endDate);
        }

        wrapper.orderByDesc(CompletionOfProductionDayBctj14::getStatisticsDate);

        List<CompletionOfProductionDayBctj14> records = list(wrapper);
        List<Map<String, Object>> result = new ArrayList<>();

        for (CompletionOfProductionDayBctj14 record : records) {
            Map<String, Object> item = new HashMap<>();
            item.put("id", record.getId());
            item.put("statisticsDate", record.getStatisticsDate());
            item.put("zjjhcl", record.getZjjhcl());
            item.put("zjwccl", record.getZjwccl());
            item.put("zjwcbl", calculateCompletionRatio(record.getZjwccl(), record.getZjjhcl()));
            item.put("zjxc", record.getZjxc());
            item.put("jsjhcl", record.getJsjhcl());
            item.put("jswccl", record.getJswccl());
            item.put("jswcbl", calculateCompletionRatio(record.getJswccl(), record.getJsjhcl()));
            item.put("jsxc", record.getJsxc());
            item.put("zbzbjhcl", record.getZbzbjhcl());
            item.put("zbzbwccl", record.getZbzbwccl());
            item.put("zbzbwcbl", calculateCompletionRatio(record.getZbzbwccl(), record.getZbzbjhcl()));
            item.put("zbzbxc", record.getZbzbxc());
            item.put("updateTime", record.getUpdateTime());
            result.add(item);
        }

        return result;
    }

    @Override
    public List<Map<String, Object>> getWarpingStatistics(String startDate, String endDate) {
        List<Map<String, Object>> result = new ArrayList<>();

        LambdaQueryWrapper<CompletionOfProductionDayBctj14> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(startDate)) {
            wrapper.ge(CompletionOfProductionDayBctj14::getStatisticsDate, startDate);
        }
        if (StringUtils.hasText(endDate)) {
            wrapper.le(CompletionOfProductionDayBctj14::getStatisticsDate, endDate);
        }
        wrapper.orderByDesc(CompletionOfProductionDayBctj14::getStatisticsDate);

        List<CompletionOfProductionDayBctj14> records = list(wrapper);

        for (CompletionOfProductionDayBctj14 record : records) {
            Map<String, Object> item = new HashMap<>();
            item.put("date", formatDate(record.getStatisticsDate()));
            item.put("plannedProduction", record.getZjjhcl());
            item.put("actualProduction", record.getZjwccl());
            item.put("completionRatio", calculateCompletionRatio(record.getZjwccl(), record.getZjjhcl()));

            result.add(item);
        }

        return result;
    }

    @Override
    public List<Map<String, Object>> getSizingStatistics(String startDate, String endDate) {
        List<Map<String, Object>> result = new ArrayList<>();

        LambdaQueryWrapper<CompletionOfProductionDayBctj14> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(startDate)) {
            wrapper.ge(CompletionOfProductionDayBctj14::getStatisticsDate, startDate);
        }
        if (StringUtils.hasText(endDate)) {
            wrapper.le(CompletionOfProductionDayBctj14::getStatisticsDate, endDate);
        }
        wrapper.orderByDesc(CompletionOfProductionDayBctj14::getStatisticsDate);

        List<CompletionOfProductionDayBctj14> records = list(wrapper);

        for (CompletionOfProductionDayBctj14 record : records) {
            Map<String, Object> item = new HashMap<>();
            item.put("date", formatDate(record.getStatisticsDate()));
            item.put("plannedProduction", record.getJsjhcl());
            item.put("actualProduction", record.getJswccl());
            item.put("completionRatio", calculateCompletionRatio(record.getJswccl(), record.getJsjhcl()));

            result.add(item);
        }

        return result;
    }

    @Override
    public List<Map<String, Object>> getWeavingStatistics(String startDate, String endDate) {
        List<Map<String, Object>> result = new ArrayList<>();

        LambdaQueryWrapper<CompletionOfProductionDayBctj14> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(startDate)) {
            wrapper.ge(CompletionOfProductionDayBctj14::getStatisticsDate, startDate);
        }
        if (StringUtils.hasText(endDate)) {
            wrapper.le(CompletionOfProductionDayBctj14::getStatisticsDate, endDate);
        }
        wrapper.orderByDesc(CompletionOfProductionDayBctj14::getStatisticsDate);

        List<CompletionOfProductionDayBctj14> records = list(wrapper);

        for (CompletionOfProductionDayBctj14 record : records) {
            Map<String, Object> item = new HashMap<>();
            item.put("date", formatDate(record.getStatisticsDate()));
            item.put("standardizedPlan", record.getZbzbjhcl());
            item.put("actualStandardized", record.getZbzbwccl());
            item.put("completionRatio", calculateCompletionRatio(record.getZbzbwccl(), record.getZbzbjhcl()));

            result.add(item);
        }

        return result;
    }

    /**
     * 格式化日期显示
     */
    private String formatDate(String date) {
        if (StringUtils.hasText(date) && date.length() >= 10) {
            return date.substring(5, 10); // 返回 MM-dd 格式
        }
        return date;
    }

    /**
     * 计算完成率 (完成产量 / 计划产量 * 100)
     */
    private BigDecimal calculateCompletionRatio(BigDecimal actual, BigDecimal planned) {
        if (actual == null || planned == null || planned.compareTo(BigDecimal.ZERO) == 0) {
            return BigDecimal.ZERO;
        }
        return actual.divide(planned, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100"));
    }

    @Override
    public List<Map<String, Object>> getWarpingStatisticsByMonth(Integer year, Integer month) {
        String startDate = getBusinessMonthStartDate(year, month);
        String endDate = getBusinessMonthEndDate(year, month);
        return getWarpingStatistics(startDate, endDate);
    }

    @Override
    public List<Map<String, Object>> getSizingStatisticsByMonth(Integer year, Integer month) {
        String startDate = getBusinessMonthStartDate(year, month);
        String endDate = getBusinessMonthEndDate(year, month);
        return getSizingStatistics(startDate, endDate);
    }

    @Override
    public List<Map<String, Object>> getWeavingStatisticsByMonth(Integer year, Integer month) {
        String startDate = getBusinessMonthStartDate(year, month);
        String endDate = getBusinessMonthEndDate(year, month);
        return getWeavingStatistics(startDate, endDate);
    }

    @Override
    public List<Map<String, Object>> getZlStatisticsByMonth(Integer year, Integer month) {
        String startDate = getBusinessMonthStartDate(year, month);
        String endDate = getBusinessMonthEndDate(year, month);
        return getZlStatistics(startDate, endDate);
    }

    @Override
    public List<Map<String, Object>> getZlStatistics(String startDate, String endDate) {
        List<Map<String, Object>> result = new ArrayList<>();

        LambdaQueryWrapper<CompletionOfProductionDayBctj14> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(startDate)) {
            wrapper.ge(CompletionOfProductionDayBctj14::getStatisticsDate, startDate);
        }
        if (StringUtils.hasText(endDate)) {
            wrapper.le(CompletionOfProductionDayBctj14::getStatisticsDate, endDate);
        }
        wrapper.orderByDesc(CompletionOfProductionDayBctj14::getStatisticsDate);

        List<CompletionOfProductionDayBctj14> records = list(wrapper);

        for (CompletionOfProductionDayBctj14 record : records) {
            Map<String, Object> item = new HashMap<>();
            item.put("date", formatDate(record.getStatisticsDate()));
            item.put("standardizedPlan", record.getZljhcl());
            item.put("actualStandardized", record.getZlwccl());
            item.put("completionRatio", calculateCompletionRatio(record.getZlwccl(), record.getZljhcl()));
            result.add(item);
        }

        return result;
    }

    /**
     * 获取指定年月的最后一天
     */
    private String getLastDayOfMonth(int year, int month) {
        java.time.LocalDate lastDay = java.time.LocalDate.of(year, month, 1).plusMonths(1).minusDays(1);
        return lastDay.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    /**
     * 获取业务月份开始日期（上月21号）
     * @param year 年份
     * @param month 月份
     * @return 业务月份开始日期，格式：yyyy-MM-dd
     */
    private String getBusinessMonthStartDate(int year, int month) {
        java.time.LocalDate currentMonth = java.time.LocalDate.of(year, month, 1);
        java.time.LocalDate startDate = currentMonth.minusMonths(1).withDayOfMonth(21);
        return startDate.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    /**
     * 获取业务月份结束日期（本月20号）
     * @param year 年份
     * @param month 月份
     * @return 业务月份结束日期，格式：yyyy-MM-dd
     */
    private String getBusinessMonthEndDate(int year, int month) {
        java.time.LocalDate currentMonth = java.time.LocalDate.of(year, month, 1);
        java.time.LocalDate endDate = currentMonth.withDayOfMonth(20);
        return endDate.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }
}
